import { arrayMoveMutable } from 'array-move'
import Color from 'color'
import { designerThemeColorValueRegEx } from './constants'

export function noop() {}
export function cloneDeep<T = any>(value: T): T {
  return 'structuredClone' in window ? structuredClone(value) : JSON.parse(JSON.stringify(value))
}
export function warn(...msgs: any) {
  console.warn('[designer warn] ', ...msgs)
}
/** 
 * 统一限制主题色颜色格式仅`#RRGGBB`格式，将所有英文字母**大写**
 * @param {string} color 符合`#RRGGBB`格式的颜色值
 */
export function toUnifiedFormatColor(color: string) {
  if (!color) 
    return color
  try {
    color = Color(color).hex()
    return color.toUpperCase()
  }
  catch {
    warn(`[toUnifiedFormatColor] 颜色 ${color} 不是有效的颜色格式`)
    return color
  }
}
/** 颜色格式是否符合`#RRGGBB`格式 */
export function isColorMatches(color: string) {
  if (!color) 
    return false
  return designerThemeColorValueRegEx.test(color)
}
/**
 * 获取主题色的浅色模式值
 * @param themeColor 主题色
 * @param [alpha] 透明通道, 默认`0.04`
 * @description 如果传入参数非`#RRGGBB`格式， 则原样返回
 */
export function getDesignerThemeColorLight(themeColor: string, alpha = 0.04) {
  if (!isColorMatches(themeColor)) 
    return themeColor
  return Color(themeColor).alpha(alpha).string()
}
export function closeCurrentWindow() {
  window.open('', '_self', '')
  window.close()
}
export function removeItem<T = Record<string, any>>(items: T[], predicate: ArrayPredicate<T>) {
  const index = items.findIndex(predicate)
  if (~index) {
    items.splice(index, 1)
  }
}
export function sortItem<T = Record<string, any>>(items: T[], predicate: ArrayPredicate<T>, type: 'up' | 'down') {
  const index = items.findIndex(predicate)
  const isFirst = index === 0
  const isLast = index === items.length - 1
  if (type === 'up') {
    if (isFirst)
      return
    const prevIndex = index - 1
    arrayMoveMutable(items, index, prevIndex)
  }
  else if (type === 'down') {
    if (isLast)
      return
    const nextIndex = index + 1
    arrayMoveMutable(items, index, nextIndex)
  }
}
export function withResolvers<T = void>(): PromiseWithResolvers<T> {
  if ('withResolvers' in Promise) {
    // @ts-ignore
    return Promise.withResolvers()
  }
  let resolve, reject
  const promise = new Promise((_resolve, _reject) => {
    resolve = _resolve
    reject = _reject
  })
  return {
    // @ts-ignore
    resolve,
    // @ts-ignore
    reject,
    // @ts-ignore
    promise,
  }
}
